/*
 * MailServlet.java
 *
 * Created on September 10, 2007, 6:07 PM
 */
package edu.chl.project.carshop07.ctrl.servlets;



import edu.chl.project.carshop07.constants.Actions;
import edu.chl.project.carshop07.constants.Attributes;
import edu.chl.project.carshop07.constants.MailConstants;
import edu.chl.project.carshop07.constants.Pages;
import edu.chl.project.carshop07.constants.Patterns;
import edu.chl.project.carshop07.core.Customer;
import edu.chl.project.carshop07.core.ShoppingCart;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  
 * @author AMADIN
 */
@WebServlet(name = "MailServlet", urlPatterns = {Patterns.MAIL})
public class MailServlet extends HttpServlet {

    
    
    private void sendMail(String subject, String content, String receiver) 
    throws NoSuchProviderException,
    MessagingException 
    {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtps.host", MailConstants.SMTP_HOST_NAME);
        props.put("mail.smtps.auth", "true");
        // props.put("mail.smtps.quitwait", "false");

        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        message.setContent(content, "text/plain");

        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(receiver));

        transport.connect(
                MailConstants.SMTP_HOST_NAME, 
                MailConstants.SMTP_HOST_PORT, 
                MailConstants.SMTP_AUTH_USER,
                MailConstants.SMTP_AUTH_PWD
                );

        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //TODO exceptions
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter(Attributes.ACTION);
        boolean trouble = false;

        if (Actions.MAIL.equals(action)) {
   
            ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute(Attributes.CART);
            String receiver = ((Customer) request.getSession().getAttribute(Attributes.USER))
                    .getPersonalData().getEmail();
            request.getRequestDispatcher(Pages.CONFIRM).forward(request, response);
            try {
                sendMail("Confirmation", cart.toString(), receiver);
            } catch (NoSuchProviderException ex) {
                request.getSession().setAttribute(Attributes.MSG, ex.getLocalizedMessage());
                trouble = true;
            } catch (MessagingException ex) {
                request.getSession().setAttribute(Attributes.MSG, ex.getLocalizedMessage());
                trouble = true;
            } finally {
                if (trouble) {
                    request.getRequestDispatcher(Patterns.MSG).forward(request, response);
                }else
                    response.sendRedirect(Pages.CONFIRM);
            }


        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
         */
        @Override
        protected void doGet
        (HttpServletRequest request, HttpServletResponse response
        )
            throws ServletException
        , IOException {
            processRequest(request, response);




        }

        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
         */
        @Override
        protected void doPost
        (HttpServletRequest request, HttpServletResponse response
        )
            throws ServletException
        , IOException {
            processRequest(request, response);




        }

        /** Returns a short description of the servlet.
         */
        @Override
        public String getServletInfo
        
            () {
        return "Short description";


        }
        // </editor-fold>
    }
